package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.HeadingWindowData;
import com.ironman.common.params.HeadingParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class HeadingPostHandler extends BasePostHandler<HeadingWindowData> {

    private Double preHeadingT = null;

    private final HeadingParam headingParam;

    public HeadingPostHandler(HeadingParam headingParam) {
        this.headingParam = headingParam;
    }

    @Override
    public void handler(HeadingWindowData data, Consumer<HeadingWindowData> consumer) {
        doHandler(data, consumer);
    }

    @Override
    public void threshold(HeadingWindowData data) {
        Double headingT = data.getHeadingT();
        if (Objects.isNull(headingT)) {
            return;
        }

        if (preHeadingT == null) {
            getCounter().incrementAndGet();
            preHeadingT = headingT;
            return;
        }

        Integer headingThreshold = headingParam.getHeadingThreshold();
        double diff = Math.abs(headingT - preHeadingT);
        diff = diff > 180 ? 360 - diff : diff;
        if (diff > headingThreshold) {
            getCounter().set(0);
            log.debug("航向触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", headingThreshold, headingT, preHeadingT, diff);
            preHeadingT = headingT;
            return;
        }

        Integer countThreshold = headingParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.debug("航向触发数量阈值:{} ", countThreshold);
            preHeadingT = headingT;
            return;
        }
        data.setHeadingT(preHeadingT);
    }

}
